package com.example.shiwu.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.example.shiwu.db.dao.BoxEightDao;
import com.example.shiwu.db.dao.SendVoDao;
import com.example.shiwu.db.dao.SendsDao;
import com.example.shiwu.db.dao.base.BaseDaoFactory;
import com.example.shiwu.db.model.BoxEight;
import com.example.shiwu.db.model.Sends;
import com.example.shiwu.db.vo.SendVo;
import com.example.shiwu.fragment.MainRoutineFragment;
import com.example.shiwu.manager.DatabaseHelper;
import com.example.shiwu.util.DateUtils;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.util.IdUtil;

public class SendsService extends Service {

    private DatabaseHelper dbHelper;
    private SendsDao<Sends> SendsDao;
    private SendVoDao<SendVo> sendVoDao;
    private ArrayList<Sends> listSends = new ArrayList<>();

    private static final int PAGE_SIZE = 10;
    private static final int TOTAL_PAGE = 0;
    private static Context appContext;

    @Override
    public void onCreate() {
        super.onCreate();
        appContext = this; // 等价于 getApplicationContext() 吗？往下看！
        // 使用 context 执行操作（如获取资源、启动组件等）
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public List<SendVo> getAll(Integer currentPage, Integer pageSize,Integer itemId,int type){
        sendVoDao = BaseDaoFactory.getInstance().createBaseDao(SendVoDao.class, SendVo.class);
        SendVo send = new SendVo();
//        List<SendVo> lis = sendVoDao.query(send,"tb_sends send left join " +
//                        " tb_receive receive on send.item_id = receive.item_id left join" +
//                        " tb_items ite on ite.id = receive.item_id left join tb_device dev on dev.item_id = ite.id",
//                new String[]{"ite.id","ite.name","dev.sn as deviceId","dev.device_type as deviceType","send.voltage","send.electricity","send.send_frequency as sendFrequency","send.send_duration as sendDuration","send.send_local as sendLocal","send.operator","receive.receive_local as receiveLocal"},
//                "ite.id =?",new String[]{String.valueOf(itemId)},"ite.id","send.create_time","",currentPage,pageSize);
        List<SendVo> lis = sendVoDao.query(send,"tb_sends send left join " +
                        " tb_items ite on ite.id = send.item_id left join tb_device dev on dev.item_id = ite.id left join tb_arrange arr on arr.item_id = send.item_id ",
                new String[]{"send.id","ite.name","send.item_id","ite.operator","dev.sn as deviceId","send.repeat_num","send.voltage as voltages","send.create_time","send.send_frequency","send.uid","arr.device_type"},
                "send.status = 0 and send.type = ? and ite.id =?",new String[]{String.valueOf(type),String.valueOf(itemId)},"send.id","send.id"+" DESC","",currentPage,pageSize);
        return lis;
    }
    public List<SendVo> getAll1(Integer currentPage, Integer pageSize,Integer itemId,int type){
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        sendVoDao = BaseDaoFactory.getInstance().createBaseDao(SendVoDao.class, Sends.class);
        SendVo send = new SendVo();
//        List<SendVo> lis = sendVoDao.query(send,"tb_sends send left join " +
//                        " tb_receive receive on send.item_id = receive.item_id left join" +
//                        " tb_items ite on ite.id = receive.item_id left join tb_device dev on dev.item_id = ite.id",
//                new String[]{"ite.id","ite.name","dev.sn as deviceId","dev.device_type as deviceType","send.voltage","send.electricity","send.send_frequency as sendFrequency","send.send_duration as sendDuration","send.send_local as sendLocal","send.operator","receive.receive_local as receiveLocal"},
//                "ite.id =?",new String[]{String.valueOf(itemId)},"ite.id","send.create_time","",currentPage,pageSize);
        List<SendVo> lis = sendVoDao.query(send,"tb_sends send left join " +
                        " tb_items ite on ite.id = send.item_id left join tb_device dev on dev.item_id = ite.id left join tb_arrange arr on arr.item_id = send.item_id ",
                new String[]{"send.id","ite.name","send.item_id","ite.operator","dev.sn as deviceId","send.repeat_num","send.voltage as voltages","send.create_time","send.send_frequency","send.uid","arr.device_type"},
                "send.status = 0 and send.type = ? and ite.id =?",new String[]{String.valueOf(type),String.valueOf(itemId)},"send.id","send.id"+" DESC","",currentPage,pageSize);
        return lis;
    }

    /**获取单个数据
     * @param sends
     * @return
     */
    public List<Sends> getSends(Sends sends) {
        listSends = new ArrayList<>();
        SendsDao = BaseDaoFactory.getInstance().createBaseDao(SendsDao.class, Sends.class);
        listSends.addAll(SendsDao.query(sends));
        return listSends;
    }

    /**
     * 获取单个数据
     *
     * @param sends
     * @param mainRoutineFragment
     * @return
     */
    public List<Sends> getSends(Sends sends, Context context) {
        dbHelper = new DatabaseHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String itemId = String.valueOf(sends.getItemId());
        // 查询条件
        String[] projection = {"id,item_id,uid,voltage,electricity,repeat_num,send_frequency,filter_frequency," +
                "send_duration,send_local,error_point,boxaddr,operator,type,status,create_time,update_time"}; // 要返回的列
        String selection = "item_id = ?"; // 查询条件（相当于 WHERE 子句）
        String[] selectionArgs = {String.valueOf(sends.getItemId())}; // 条件参数，会替换上面的 ?
        String sortOrder = "id DESC"; // 排序方式

        // 执行查询
        Cursor cursor = db.query(
                "tb_sends", // 表名
                projection,
                selection,
                new String[]{itemId},
                null, // GROUP BY
                null, // HAVING
                sortOrder
        );
        List<Sends> lis = new ArrayList<>();
        while (cursor.moveToNext()) {
            Sends sends1 = new Sends();
            String id = cursor.getString(0);
            sends1.setId(Integer.valueOf(id));
            int itemId1 = cursor.getInt(1);
            sends1.setItemId(itemId1);
            String uid = cursor.getString(2);
            sends1.setUid(uid);
            String voltage = cursor.getString(3);
            sends1.setVoltage(voltage);
            String electricity = cursor.getString(4);
            sends1.setElectricity(electricity);
            String repeat_num = cursor.getString(5);
            sends1.setRepeatNum(repeat_num);
            String send_frequency = cursor.getString(6);
            sends1.setSendFrequency(send_frequency);

            String filter_frequency = cursor.getString(7);
            sends1.setFilterFrequency(filter_frequency);
            String send_duration = cursor.getString(8);
            sends1.setSendDuration(send_duration);
            String send_local = cursor.getString(9);
            sends1.setUid(send_local);
            String error_point = cursor.getString(10);
            sends1.setErrorPoint(error_point);
            String boxaddr = cursor.getString(11);
            //sends1.setBoxaddr(boxaddr);
            String operator = cursor.getString(12);
            //sends1.setBoxaddr(operator);
            int type = cursor.getInt(13);
            sends1.setType(type);
            int status = cursor.getInt(14);
            sends1.setStatus(status);
            String create_time = cursor.getString(15);
            sends1.setCreateTime(create_time);
            String up_time = cursor.getString(16);
            sends1.setUpdateTime(up_time);

            lis.add(sends1);
        }
        return lis;
    }
    public List<Sends> getSendsLast(Sends sends) {
        listSends = new ArrayList<>();
        SendsDao = BaseDaoFactory.getInstance().createBaseDao(SendsDao.class, Sends.class);
        listSends.addAll(SendsDao.queryLast(sends,"id desc"));
        return listSends;
    }

    /**分页获取数据
     * @param sends
     * @return
     */
    public List<Sends> getSendsList(Sends sends,Integer startIndex,Integer limit) {
        SendsDao = BaseDaoFactory.getInstance().createBaseDao(SendsDao.class, Sends.class);
        listSends = new ArrayList<>();
        listSends.addAll(SendsDao.query(sends,null,"create_time desc",null,startIndex,limit));
        return listSends;
    }

    public boolean save(Sends sends) {
        SendsDao = BaseDaoFactory.getInstance().createBaseDao(SendsDao.class, Sends.class);
        long size = SendsDao.insert(sends);
        if(size >0 ){
            return true;
        }
        return false;
    }
    public boolean saveOrUpdata(Sends sends,Sends sends2) {
        SendsDao = BaseDaoFactory.getInstance().createBaseDao(SendsDao.class, Sends.class);
        Sends sends1 = new Sends();
        sends1.setItemId(sends.getItemId());
        sends1.setType(sends2.getType());
        sends1.setId(sends2.getId());
        List<Sends> lis =SendsDao.query(sends1);
        Boolean bl = true;
        if(lis.size()>0){
            sends.setUpdateTime(DateUtils.parseDate());
            long size = SendsDao.update(sends,sends1);
            if(size >0 ){
                return bl;
            }
            bl = false;
        }else{
            String simpleUUID = IdUtil.simpleUUID();
            sends.setUid(simpleUUID);
            sends.setCreateTime(DateUtils.parseDate());
            long size = SendsDao.insert(sends);
            if(size >0 ){
                return bl;
            }
            bl = false;
        }

        return bl;
    }


    public boolean updade(Sends sends,Sends where) {
        SendsDao = BaseDaoFactory.getInstance().createBaseDao(SendsDao.class, Sends.class);

        long size = SendsDao.update(sends,where);
        if(size >0 ){
            return true;
        }
        return false;
    }

    public boolean delete(Sends sends) {
        SendsDao = BaseDaoFactory.getInstance().createBaseDao(SendsDao.class, Sends.class);
        int size = SendsDao.delete(sends);
        if(size >0 ){
            return true;
        }
        return false;
    }
}
